package com.android.jay.lib_network.okhttp.response;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.android.jay.lib_network.okhttp.exception.OkHttpException;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDataHandler;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDataListener;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDownloadListener;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by wzp on 2019/12/29 0029.
 * <p>
 * 描述  ：处理文件类型的响应
 */
public class CommonFileCallback implements Callback {

    protected final String EMPTY_MSG = "";
    protected final int NETWORK_ERROR = -1;
    protected final int IO_ERROR = -2;
    private static final int PROGRESS_MESSAGE = 0x01;
    private Handler mDeliveryHandler;
    private DisposeDownloadListener mListener;
    //文件路径
    private String mFilePath;
    //文件进度
    private int mProgress;


    public CommonFileCallback(DisposeDataHandler handler) {

        this.mListener = (DisposeDownloadListener) handler.mListener;
        this.mFilePath = handler.mSource;
        this.mDeliveryHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case PROGRESS_MESSAGE:
                        mListener.onProgress((int) msg.obj);
                        break;
                }
            }

        };
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull final IOException e) {
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                mListener.onFailure(new OkHttpException(NETWORK_ERROR, e));
            }
        });
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        final File file = handleResponse(response);
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                if (file != null) {
                    mListener.onSuccess(file);
                }else{
                    mListener.onFailure(new OkHttpException(IO_ERROR,EMPTY_MSG));
                }
            }
        });

    }

    private File handleResponse(Response response) {

        if (response == null) {
            return null;
        }

        InputStream inputStream = null;
        File file = null;
        FileOutputStream fos = null;
        byte[] buffer = new byte[2048];
        int length;
        double currentLength = 0;
        double sumLength;
        try {
            checkLocalFilePath(mFilePath);
            file = new File(mFilePath);
            fos = new FileOutputStream(file);
            inputStream = response.body().byteStream();
            sumLength = (double) response.body().contentLength();
            while ((length = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0,length);
                currentLength += length;
                mProgress = (int) (currentLength / sumLength * 100);
                mDeliveryHandler.obtainMessage(PROGRESS_MESSAGE, mProgress).sendToTarget();
            }
            fos.flush();
        } catch (Exception e) {
            file = null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                file = null;
            }

        }
        return file;
    }


    /**
     * 检查是否存在
     **/
    private void checkLocalFilePath(String mFilePath) {
        File path = new File(mFilePath.substring(0,
                mFilePath.lastIndexOf("/") + 1));
        File file = new File(mFilePath,"12333.jpeg");
        if (!path.exists()){
             path.mkdirs();
        }
        if (file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
